# -*- coding: utf-8 -*-
############################################################################
from chee.shortcuts import *
from chee.models import User_Info
from chee.models.user import User_Mail
############################################################################
class MailUtil(UserAjaxHandler):
    rule = Rule('/user/mail/util/')
    def get(self):
        return self.post()
    def post(self):
        type = self.request.form.get('type',u'')
        db = self.store
        try:
            if type == u'del':
                value = self.request.form.get('value')
                mail_ids = value.split(',')
                for mid in mail_ids:
                    if mid == '':
                        continue
                    mail_id = int(mid)
                    store.find(User_Mail,User_Mail.id==mail_id).remove()
                store.commit()
                return Response(encodeJsonMsg(True,u''))
            elif type == u'delAll':
                box = self.request.form.get('box',u'')
                if box == u'recv':
                    store.find(User_Mail,User_Mail.owner_id==self.request.user.id,
                            User_Mail.to_id==self.request.user.id).remove()
                    return Response(Template("true").render())
                elif box == u'send':
                    store.find(User_Mail,User_Mail.owner_id==self.request.user.id,
                            User_Mail.from_id==self.request.user.id).remove()
                    return Response(encodeJsonMsg(True,u''))
            else:
                return Response(encodeJsonMsg(False,u'访问错误'))
        except:
            return Response(encodeJsonMsg(False,u'暂时无法连接网络，请您稍后再试。'))

class MailIndex(UserHandler):
    rule = Rule('/user/mail/')
    def get(self):
        return redirect('/user/mail/recv/')

class RecvBox(UserHandler):
    rule = Rule('/user/mail/recv/')
    def get(self):
        mails = store.find(User_Mail, User_Mail.to_id==self.request.user.id,
                        User_Mail.owner_id==self.request.user.id).order_by(Desc(User_Mail.id))
        unread = 0
        for mail in mails:
            if mail.is_read==0: unread = unread + 1
        
        page_num = 1        
        try:
            page_num = int(self.request.args.get('page', '1'))
        except ValueError:
            page_num = 1 

        paginator = Paginator(mails, 20) 
        try:
            page = paginator.page(page_num)
        except InvalidPage:
            raise NotFound

        tmpl = env.get_template('user/mail/recvbox.html')
        return Response(tmpl.render(
            request = self.request, errors = self.errors, main_active = u"myspace",
            right_active = u"recv", unread = unread, page = page
        ))
class SendBox(UserHandler):
    rule = Rule('/user/mail/send/')
    def get(self):
        mails = store.find(User_Mail, User_Mail.from_id==self.request.user.id,
                        User_Mail.owner_id==self.request.user.id).order_by(Desc(User_Mail.id))
        
        page_num = 1        
        try:
            page_num = int(self.request.args.get('page', '1'))
        except ValueError:
            page_num = 1 

        paginator = Paginator(mails, 20) 
        try:
            page = paginator.page(page_num)
        except InvalidPage:
            raise NotFound

        tmpl = env.get_template('user/mail/sendbox.html')
        return Response(tmpl.render(
            request = self.request, errors = self.errors, main_active = u"myspace",
            right_active = u"send", page = page
        ))
class NewMail(UserHandler):
    rule = Rule('/user/mail/new/')
    def post(self):
        try:
            tmp_uids = self.request.form.get('to_ids', u'').strip()
            title = self.request.form.get('title', u'').strip()
            content = self.request.form.get('content', u'').strip()
            bw = ban_word(content)
            if bw != None:
                return Response(encodeJsonMsg(False,u'消息内容包含敏感词汇\"%s\", 请更换' % bw))
            if title:
                bw = ban_word(title)
                if bw != None:
                    return Response(encodeJsonMsg(False,u'消息标题包含敏感词汇\"%s\", 请更换' % bw))
            uids = tmp_uids.split(',')
            for uid_str in uids:
                if uid_str != '':
                    uid = int(uid_str)
                    usr = store.find(User_Info,User_Info.id==uid).one()
                    info = u''
                    if not usr:
                        return Response(encodeJsonMsg(False,u'找不到某个或多个收件人'))
                    elif usr.id==self.request.user.id:
                        return Response(encodeJsonMsg(False,u'不能给自己发消息'))
                    else:
                        mail = User_Mail()
                        mail.owner_id = self.request.user.id
                        mail.from_id = self.request.user.id
                        mail.to_id = usr.id
                        mail.title = toHtml(title)
                        mail.content = toHtml(content)
                        mail.send_time = datetime.now()
                        mail.is_read = 0
                        
                        store.add(mail)
                        nmail = User_Mail()
                        nmail.owner_id = usr.id
                        nmail.from_id = self.request.user.id
                        nmail.to_id = usr.id
                        nmail.title = toHtml(title)
                        nmail.content = toHtml(content)
                        nmail.send_time = datetime.now()
                        nmail.is_read = 0
                        store.add(nmail)
            store.commit()
            msg = encodeJsonMsg(True,u'发送消息成功')
            return Response(msg)
        except:
            return Response(encodeJsonMsg(False,u'暂时无法连接网络，请您稍后再试。'))

class MailDetail(UserHandler):
    rule = Rule('/user/mail/<int:mail_id>/')
    def get(self):
        mail_id = self.kwargs['mail_id']
        db = self.store
        mail = store.find(User_Mail,User_Mail.id==mail_id).one()
        if not mail:
            tmpl = env.get_template('user/mail/info.html')
            return MailInfo(self.request, self.errors, u'该消息已被删除')
        elif mail.owner_id != self.request.user.id:
            tmpl = env.get_template('user/mail/info.html')
            return MailInfo(self.request,self.errors,u'您不能查看该消息')
            
        active = u''
        if mail.owner_id == mail.from_id:
            active = u'send'
        elif mail.owner_id == mail.to_id:
            active = u'recv'
        
        if mail.is_read==0:
            mail.is_read = 1
            store.add(mail)
            store.commit()
        
        tmpl = env.get_template('user/mail/mail_detail.html')
        return Response(tmpl.render(
            request = self.request,
            errors = self.errors,
            main_active = u"myspace",
            right_active = active,
            this_mail = mail
        ))

class MailReply(UserAjaxHandler):
    rule = Rule('/user/mail/reply/')
    def post(self):
        try:
            mail_id = int(self.request.form.get('mail_id', u'').strip())
            title = self.request.form.get('title', u'').strip()
            content = self.request.form.get('content', u'').strip()
            bw = ban_word(content)
            if bw != None:
                msg = encodeJsonMsg(False,u'消息内容包含敏感词汇\"%s\", 请更换' % bw)
                return Response(msg)
            if title:
                bw = ban_word(title)
                if bw != None:
                    msg = encodeJsonMsg(False,u'消息标题包含敏感词汇\"%s\", 请更换' % bw)
                    return Response(msg)
            else:
                title = content[:10]
            mail = store.find(User_Mail,User_Mail.id==mail_id).one()
            if not mail:
                return Response(encodeJsonMsg(False,u'要回复的消息不存在'))
            
            reply = User_Mail()
            reply.owner_id = mail.from_id
            reply.from_id = mail.to_id
            reply.to_id = mail.from_id
            reply.title = toHtml(title)
            reply.content = toHtml(content)
            reply.send_time = datetime.now()
            reply.is_read = 0
    
            nreply = User_Mail()
            nreply.owner_id = mail.to_id
            nreply.from_id = mail.to_id
            nreply.to_id = mail.from_id
            nreply.title = toHtml(title)
            nreply.content = toHtml(content)
            nreply.send_time = datetime.now()
            nreply.is_read = 0
    
            store.add(reply)
            store.add(nreply)
            store.commit()
            
            info = u'发送消息成功'
            
            return Response(encodeJsonMsg(True,u''))
        except:
            return Response(encodeJsonMsg(False,u'暂时无法连接网络，请您稍后再试。'))
           